package com.ceprei.gui.web;

import org.apache.catalina.connector.RequestFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zhou minghao
 * @date 2024/11/27
 * @description
 */
@Component
@Order(1)
public class CorsFilter implements Filter {

    @Autowired
    private CorsProperties corsProperties;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        List<String> accessControlAllowOrigin = corsProperties.getAccessControlAllowOrigin();
        String originHeader = ((RequestFacade) req).getHeader("Origin");
        if (accessControlAllowOrigin.contains(originHeader)) {
            response.setHeader("Access-Control-Allow-Origin", originHeader);

            response.setHeader("Access-Control-Allow-Methods", corsProperties.getAccessControlAllowMethods());

            response.setHeader("Access-Control-Max-Age", corsProperties.getAccessControlMaxAge());

            response.setHeader("Access-Control-Allow-Headers", corsProperties.getAccessControlAllowHeaders());

            response.setHeader("Access-Control-Allow-Credentials", corsProperties.getAccessControlAllowCredentials());

        }


        chain.doFilter(req, res);

    }
}
